Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports MefTZAddin.interop.types

Namespace interop
    Public Module SystemTimeInterop
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ToSystemTime(ByVal dt As DateTime) As SystemTime
            Dim st As New SystemTime()
            st.year = 0
            ' Most time zone changes are relative each year
            st.month = dt.Month

            Dim weekdayOfMonth As Integer = 1
            ' e.g. third Monday = 3...
            Dim dd As Integer = dt.Day
            'While dd > 7
            '        System.Math.Max(System.Threading.Interlocked.Increment(weekdayOfMonth), weekdayOfMonth - 1)
            '       dd -= 7
            '      End While

            While dd > 7
                weekdayOfMonth = weekdayOfMonth + 1
                dd -= 7
            End While

            st.day = weekdayOfMonth
            st.dayOfWeek = dt.DayOfWeek
            st.hour = dt.Hour
            st.minute = dt.Minute
            st.second = dt.Second
            st.milliseconds = dt.Millisecond

            Return st
        End Function

        <System.Runtime.CompilerServices.Extension()> _
        Public Function ToSystemTime(ByVal tt As TimeZoneInfo.TransitionTime) As SystemTime
            Dim st As New SystemTime()

            st.year = 0
            st.month = tt.Month
            ' 1 = January
            Dim weekdayOfMonth As Integer = 1
            ' e.g. third Monday = 3...
            Dim dd As Integer = tt.Day
            While dd > 7
                weekdayOfMonth += 1
                dd -= 7
            End While

            st.day = weekdayOfMonth
            st.dayOfWeek = tt.DayOfWeek
            ' 0 = Sunday...
            st.hour = tt.TimeOfDay.Hour
            st.minute = tt.TimeOfDay.Minute
            st.second = tt.TimeOfDay.Second
            st.milliseconds = tt.TimeOfDay.Millisecond

            Return st
        End Function
    End Module
End Namespace
